import time
import serial
from time import sleep
from utils.logger import Logger
from utils.config import logpath

usb_logger = Logger(filename=f'{logpath}/gps_device.log').logger
usb_logger.info("Receive usb data Process start!")


def receive(waittime=0.01):
    gga = None
    speed = None
    gnvtg = None
    _filter = [4, 5]
    try:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.5)
        ser.reset_input_buffer()
        ser.close()
        ser.open()

        for i in range(20):
            if i > 10:
                _filter = [2, 4, 5]
            data = ser.readline()
            data = data.decode('GBK')
            if 'GGA' in data:
                resolved = int(data.split(',')[6])
                if resolved in _filter and gga is None:
                    gga = data
            elif 'GNVTG' in data:
                _data = data.split(',')
                if len(_data) >= 10 and speed is None:
                    gnvtg = data
                    speed = float(_data[7])
            if gga is not None and speed is not None and gnvtg is not None:
                break
            if waittime:
                sleep(waittime)
            if i == 19:
                usb_logger.warning(f'gps warning, out of time: {gga}---{gnvtg}---{speed}')
                # for j in range(10):
                #     data2 = ser.readline()
                #     data2 = data2.decode('GBK')
                # print("=========", data2)
        #     ser.flushInput()
        #     ser.close()
    except:
        usb_logger.error('gps error, 请检查USB插线')
        # time.sleep(1)

    finally:
        return gga, speed, gnvtg


def recv_cyc(dict):
    cnt = 0
    dict[0] = None
    dict[1] = None
    dict[2] = None
    while True:
        data, speed, gnvtg = receive(waittime=0.01)
        if data is not None:
            dict[0] = data
            cnt = 0
        if speed is not None:
            dict[1] = speed
            dict[2] = gnvtg
            cnt = 0

        time.sleep(0.5)
        cnt += 1
        if cnt > 20:
            dict[0] = data
            dict[1] = speed
            dict[2] = gnvtg
            usb_logger.error('gps error，请检查GPS设备')


def get_data(dict):
    data = dict[0]
    speed = dict[1]
    gnvtg = dict[2]
    return data, speed, gnvtg


if __name__ == '__main__':
    recv_cyc({})
